import { Service } from 'egg';

/**
 * Test Service
 */
export default class collection extends Service {
  public async addFavorites(req) {
    let state = await this.isFavorites(req)
    if (state) {
      return 1
    }
    let res = await this.ctx.model.Collection.create({
      goods_id: req.goods_id,
      user_id: req.user_id
    })
    if (res) {
      await this.ctx.model.Goods.update(
        { heat: this.app.Sequelize.literal('heat+1') },
        {
          where: {
            id: req.goods_id
          }
        }
      )
      return res
    } else {
      throw new Error()
    }
  }
  public async removeFavorites(req) {
    let state = await this.isFavorites(req)
    if (!state) {
      return 1
    }
    let res = await this.ctx.model.Collection.destroy({
      where: {
        goods_id: req.goods_id,
        user_id: req.user_id
      }
    })
    if (res) {
      await this.ctx.model.Goods.update(
        { heat: this.app.Sequelize.literal('heat-1') },
        {
          where: {
            id: req.goods_id
          }
        }
      )
      return res
    } else {
      throw new Error()
    }
  }
  public async isFavorites(req) {
    let res = await this.ctx.model.Collection.findOne({
      where: {
        goods_id: req.goods_id,
        user_id: req.user_id
      }
    })
    if (res) {
      return true
    } else {
      return false
    }
  }
}